"""
会话存储管理器
"""
import logging
from typing import Dict, Optional, List
from threading import Lock
from datetime import datetime, timedelta

from backend.models.core import ExecutionSession, SessionStatus

logger = logging.getLogger(__name__)


class SessionManager:
    """会话管理器 - 管理执行会话的生命周期"""
    
    def __init__(self):
        self._sessions: Dict[str, ExecutionSession] = {}
        self._lock = Lock()
        self._cleanup_interval = timedelta(hours=24)  # 24小时后清理会话
    
    def create_session(self, question_id: str) -> ExecutionSession:
        """创建新会话"""
        with self._lock:
            session = ExecutionSession(question_id=question_id)
            self._sessions[session.id] = session
            logger.info(f"Created new session: {session.id}")
            return session
    
    def get_session(self, session_id: str) -> Optional[ExecutionSession]:
        """获取会话"""
        with self._lock:
            return self._sessions.get(session_id)
    
    def update_session(self, session: ExecutionSession) -> bool:
        """更新会话"""
        with self._lock:
            if session.id in self._sessions:
                self._sessions[session.id] = session
                logger.debug(f"Updated session: {session.id}")
                return True
            return False
    
    def delete_session(self, session_id: str) -> bool:
        """删除会话"""
        with self._lock:
            if session_id in self._sessions:
                del self._sessions[session_id]
                logger.info(f"Deleted session: {session_id}")
                return True
            return False
    
    def list_sessions(self, status: Optional[SessionStatus] = None) -> List[ExecutionSession]:
        """列出会话"""
        with self._lock:
            sessions = list(self._sessions.values())
            if status:
                sessions = [s for s in sessions if s.status == status]
            return sessions
    
    def get_active_sessions(self) -> List[ExecutionSession]:
        """获取活跃会话"""
        active_statuses = {
            SessionStatus.ANALYZING,
            SessionStatus.TASK_PLANNING,
            SessionStatus.WAITING_CONFIRMATION,
            SessionStatus.EXECUTING
        }
        return self.list_sessions(None)  # 先获取所有会话
    
    def cleanup_old_sessions(self) -> int:
        """清理过期会话"""
        with self._lock:
            cutoff_time = datetime.now() - self._cleanup_interval
            old_session_ids = []
            
            for session_id, session in self._sessions.items():
                # 清理已完成或失败的旧会话
                if (session.status in {SessionStatus.COMPLETED, SessionStatus.FAILED, SessionStatus.CANCELLED} 
                    and session.created_at < cutoff_time):
                    old_session_ids.append(session_id)
            
            for session_id in old_session_ids:
                del self._sessions[session_id]
            
            if old_session_ids:
                logger.info(f"Cleaned up {len(old_session_ids)} old sessions")
            
            return len(old_session_ids)
    
    def get_session_count(self) -> int:
        """获取会话总数"""
        with self._lock:
            return len(self._sessions)
    
    def get_session_statistics(self) -> Dict[str, int]:
        """获取会话统计信息"""
        with self._lock:
            stats = {}
            for status in SessionStatus:
                stats[status.value] = len([s for s in self._sessions.values() if s.status == status])
            stats['total'] = len(self._sessions)
            return stats


# 全局会话管理器实例
session_manager = SessionManager()